package proxy; /**
 * Copyright (C), 2015-2018, 北京译泰教育科技有限公司
 * FileName: CGLibProxy
 * Author:   andy
 * Date:     18/1/30 下午5:32
 * Description: ${DESCRIPTION}
 * History:
 */

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author andy
 * @version V1.0
 * @date 18/1/30 下午5:32
 */
public class CGLibProxy implements MethodInterceptor{

    private static CGLibProxy cgLibProxy = new CGLibProxy();

    public static CGLibProxy getInstance(){
        return cgLibProxy;
    }

    public <T> T getProxy(Class<T> cls){
        return (T)Enhancer.create(cls, this);
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invokeSuper(o, objects);
        after();
        return result;
    }

    private void before() {
        System.out.println("before：" + System.currentTimeMillis());
    }

    private void after() {
        System.out.println("after：" + System.currentTimeMillis());
    }

    public static void main(String[] args) {
        //CGLibProxy cgLibProxy = new CGLibProxy();
        //Hello helloProxy = cgLibProxy.getProxy(HelloImpl.class);
        //helloProxy.say();

        Hello helloProxy = CGLibProxy.getInstance().getProxy(HelloImpl.class);
        helloProxy.say();
    }
}
